package com.orharlan.carassistant.gui;

import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orharlan.carassistant.R;
import com.orharlan.carassistant.datamodel.Datamodel;

public class SplashSceenActivity extends Activity
{
	private static final long UNLOCK_TIME = 3000; // The user has to scale for
	                                              // at
	// least 3 seceonds;

	public static Datamodel data;

	private TextView splashScreenTv;
	private TextView countDownTv;
	private LinearLayout linLayout;

	private ScaleGestureDetector scaleGestureDetector;
	private CountDownTimer countDown;

	Context context;

	@Override
	protected void onCreate( Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );
		setContentView( R.layout.activity_splashscreen );
		context = this;

		// Refer the Textview and the LinearLayout
		splashScreenTv = (TextView) findViewById( R.id.splashScreenTv );
		countDownTv = (TextView) findViewById( R.id.countDownTv );
		linLayout = (LinearLayout) findViewById( R.id.linLayoutSplash );

		// Set fonts
		Typeface tf = Typeface.createFromAsset( getAssets( ), "fonts/myFont.ttf" );
		splashScreenTv.setTypeface( tf );

		// Call Datamodel
		data = Datamodel.singleton( );

		// Initialize the countdown to unlock the screen
		countDown = new CountDown( UNLOCK_TIME, 1000 ); // The tick
		// period is 1 seconds

		// Set listener
		scaleGestureDetector = new ScaleGestureDetector( this, new simpleOnScaleGestureListener( ) );

		// that the right textsize for the specified device
		splashScreenTv.setTextSize( 20 * getResources( ).getDisplayMetrics( ).density );

		// Check if Google Services is avaible
		if( !isGoogleMapsInstalled( ) )
		{
			Builder builder = new AlertDialog.Builder( this );
			builder.setMessage( "Install Google Maps" );
			builder.setCancelable( false );
			builder.setPositiveButton( "Install", getGoogleMapsListener( ) );
			AlertDialog dialog = builder.create( );
			dialog.show( );
		}
	}

	@Override
	public boolean onTouchEvent( MotionEvent event )
	{
		// TODO Auto-generated method stub
		scaleGestureDetector.onTouchEvent( event );
		return true;
	}

	public class simpleOnScaleGestureListener extends SimpleOnScaleGestureListener
	{

		@Override
		public boolean onScale( ScaleGestureDetector detector )
		{

			// scaleGesture.setText(String.valueOf(detector.getScaleFactor()));
			return true;
		}

		@Override
		public boolean onScaleBegin( ScaleGestureDetector detector )
		{
			countDown.start( );
			// start the animation of the background
			// animate from your current color to red
			animateBetweenColors( linLayout, R.color.backgroundColour, Color.RED, UNLOCK_TIME );
			return true;
		}

		@Override
		public void onScaleEnd( ScaleGestureDetector detector )
		{
			countDown.cancel( );
			countDownTv.setText( "" );
			linLayout.setBackgroundColor( getResources( ).getColor( R.color.backgroundColour ) );
		}

	}

	public static void animateBetweenColors( final View viewToAnimateItBackground, final int colorFrom, final int colorTo, final long durationInMs )
	{
		final ValueAnimator colorAnimation = ValueAnimator.ofObject( new ArgbEvaluator( ), colorFrom, colorTo );
		colorAnimation.addUpdateListener( new AnimatorUpdateListener( )
		{
			ColorDrawable colorDrawable = new ColorDrawable( colorFrom );

			@SuppressWarnings( "deprecation" )
            @Override
			public void onAnimationUpdate( final ValueAnimator animator )
			{
				colorDrawable.setColor( (Integer) animator.getAnimatedValue( ) );
				viewToAnimateItBackground.setBackgroundDrawable( colorDrawable );
			}
		} );
		if( durationInMs >= 0 )
			colorAnimation.setDuration( durationInMs );
		colorAnimation.start( );
	}

	public class CountDown extends CountDownTimer
	{

		public CountDown( long millisInFuture, long countDownInterval )
		{
			super( millisInFuture, countDownInterval );

		}

		@Override
		public void onFinish( )
		{
			context.startActivity( new Intent( context, MainActivity.class ) );

		}

		@Override
		public void onTick( long millisUntilFinished )
		{
			countDownTv.setText( getString( R.string.countDownTv ) + " " + millisUntilFinished / 1000 );

		}

	}

	public boolean isGoogleMapsInstalled( )
	{
		try
		{
			@SuppressWarnings( "unused" )
            ApplicationInfo info = getPackageManager( ).getApplicationInfo( "com.google.android.apps.maps", 0 );
			return true;
		}
		catch( PackageManager.NameNotFoundException e )
		{
			return false;
		}
	}

	public OnClickListener getGoogleMapsListener( )
	{
		return new OnClickListener( )
		{
			@Override
			public void onClick( DialogInterface dialog, int which )
			{
				Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( "market://details?id=com.google.android.apps.maps" ) );
				startActivity( intent );

				// Finish the activity so they can't circumvent the check
				finish( );
			}
		};
	}
}
